import React from 'react';
import './css/detail.less';
import http from '../../utils/http';
import Modal from '../components/Modal2';
const queryString = require('query-string');
const classBg = {
  backgroundImage: `url(${require("../../images/class_bg.png")})`,
  backgroundSize: '100% 100%',
  border: '0'
}
const timeBg = {
  backgroundImage: `url(${require("../../images/time_bg.png")})`,
  backgroundSize: '100% 100%',
  border: '0'
}
const groupBg = {
  backgroundImage: `url(${require("../../images/class_group.png")})`,
  height: '430px',
  marginTop: '34px',
  paddingTop: '67px',
}
class GoodsDetail extends React.Component {
  state = {
    productId: '',
    products: {
      orderClassList: {}
    },
    curTimes: [],
    selectedClass: {},  // 选中的班次
    selectedTimes: {} ,// 选中的时段
    tdShow:false,//是否显示模态框
    evaluation:"", //模态框内容
    classBg: {},  // 选中班级样式
    timeBg: {},  // 选中课时样式
    selectKey: '' // 选中的key
  }
  // 获取详情信息
  getProduct = (productId) => {
    http
      .get('/product/find/productInfo', {
        params: {
          productId
        }
      })
      .then(data => {
        this.setState({
          products: data || {}
        })
      }, err => {
      })
  }
  // 选班次
  selectClass = (item) => {
    // this.setState({curTimes: item.classVoList})
    this.getBgCss(1, 1)
    this.setState({
      selectKey: item.key,
      selectedClass: item,
      selectedTimes: {}
    })
  }
  // 选时段
  selectTimes = (item) => {
    const times = this.state.selectedTimes
    if (times.hasOwnProperty(item.key)) {
      delete times[item.key];
    } else {
      times[item.key] = item.timeVal
    }
    this.setState({
      selectedTimes: times,
      selectKey: item.key
    })
    this.getBgCss(2, 1)
  }
  // 创建订单
  createOrder = () => {
    const times = this.state.selectedTimes
    const data = {
      signIds: Object.keys(times),
      productId: this.state.productId,
      orderClassId: this.state.selectedClass.key
    }
    if(!data.orderClassId){
      this.setState({
        evaluation:'请您选择上课班次',
        tdShow:true,
      
      })
      // alert('请选择班次')
      return
    }
    if (data.signIds.length === 0) {
      this.setState({
        evaluation:'请您选择上课时间段',
        tdShow:true,
      
      })
      // alert('请选择时间段')
      return
    }
    http
    .post('/order/create/order', data)
    .then(data => {
      this.props.history.push(`/payOrder/?orderid=${data.id}`)
    }, err => {
    })
  }
  // 课程购买
  buyCourse = () => {
    this.createOrder()
    // const times = this.state.selectedTimes
    // const data = {
    //   productId: this.state.productId,
    //   orderClassId: this.state.selectedClass.id,
    //   orderClassName: this.state.selectedClass.name,
    //   signIds: Object.keys(times),
    //   presentPrice: this.state.products.presentPrice,
    //   productName: this.state.products.productName,
    //   totalClass: this.getTotalClass()
    // }
    // const nameArr = []
    // const names = Object.values(times)
    // for (const item of names) {
    //   const time = `${moment(Number(item.beginTime)).format('hh:mm')} ~ ${moment(Number(item.beginTime)).format('hh:mm')}`
    //   nameArr.push(time)
    // }
    // data.orderTimeName = nameArr.join(',')
    // const path = {
    //   pathname:'/payOrder',
    //   query:data,
    // }
    // this.props.history.push(path);
  }
  // 课程描述
  getTotalClass = () => {
    const product = this.state.products
    let str = ''
    if (product.giveClassNumber) {
      str = `${product.classNumber}赠${product.giveClassNumber}=${product.classNumber+product.giveClassNumber}课时`
    } else {
      str = `${product.classNumber}课时`
    }
    return str
  }

  // 取消弹出框事件
  notshowEvaluation= () => {
    this.setState({tdShow: false});
  }
  
  // 初始化加载钩子
  componentDidMount() {
    const search = queryString.parse(this.props.location.search)
    const productId = search.id
    if (productId) {
      this.setState({
        productId
      })
    }
    this.getProduct(productId)
  }
  // classType: 1.class 2:time showType: 1.显示样式 2.清空样式
  getBgCss = (classType, showType) => {
    if (showType === 2) {
      if (classType === 1) {
        this.setState({classBg: {}})
      } else {
        this.setState({timeBg: {}})
      }
    } else {
      if (classType === 1) {
        this.setState({classBg})
      } else {
        this.setState({timeBg})
      }
    }
  }
  render() {
    return (
      <div className="row goods-detail">
        <div className="col-md-9 detail-left">
          <div className="goback" onClick={(e)=>{
            window.history.back()
            }}>
            <img alt='' className="back-normal" src={require('../../images/icon/back_normal.png')}/>
            <img alt='' className="back-hover" src={require('../../images/icon/back_hover.png')}/>
          </div>
          <div className="changeTime">
            选择上课时间
          </div>
          <div className="title-class">班次</div>
          <div className="classes row">
            {this.state.products.dayBuckets && this.state.products.dayBuckets.map((item, index) => (
              <div className="col-md-4 col-sm-6 col-xs-12 class-item" gap="10" key={item.key}  onClick={() => this.selectClass(item)}>
                <span style={item.key===this.state.selectedClass.key?this.state.classBg:{}}>{item.dayVal}</span>
              </div>
            ))}
          </div>
          <div className="title-spliter"></div>
          <div className="title-times">时间段</div>
          <div className="times row">
            {this.state.products.dayBuckets && this.state.products.timeBuckets.map((item, index) => (
              <div className="col-md-4 col-sm-6 col-xs-12 times-item" key={index} onClick={() => this.selectTimes(item)}>
                <span style={this.state.selectedTimes[item.key]?this.state.timeBg:{}} >{item.timeVal}</span>
              </div>
            ))}
          </div>
          <div className="btn-buy row"><button className="btn btn-success" onClick={this.buyCourse}>立即购买</button></div>
        </div>
        { this.state.products.id ?
          <div className="col-md-3 detail-right">
            <div className="right-pannel"></div>
            <div className="chooseclass">选择课程包</div>
            <div className="nowprice">¥{this.state.products.presentPrice || this.state.products.originalPrice}</div>
            <div style={groupBg}>
              <div className="totalclasstime">
                {this.state.products.hourDesc}
              </div>
              <div className="right-spliter"/>
              <div className="describe">
                {this.state.products.desc}
              </div>
            </div>
          </div>
          :
          <div></div>
        }
        {/* 选择上课时间模态框 */}
        
        {
            this.state.tdShow?<Modal >
                                  <div>
                                    <header className="modal-header">  
                                     <h4 className="tip">温馨提示</h4>  
                                        <span className="tipclose"
                                            onClick={()=>{
                                                this.setState({
                                                    tdShow:!this.state.tdShow
                                                  })
                                            }}>
                                            <img src={require('../../images/XX.png')} alt="xx" /> 
                                        </span>  
                                    </header>  
                                    <div className="modal-body">  
                                      <p className="testclass"> {this.state.evaluation}</p>
                                    </div>  
                                    <footer className="modal-footer tip-footer">  
                                      <p className="cancel" onClick={this.notshowEvaluation}>知道了</p>  
                                      
                                    </footer>  
                                  </div>
                              </Modal>:''
           }  



      </div>
    );
  }
}
export default GoodsDetail;